package forums.web;

import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import forums.model.Forum;
import forums.model.Message;
import forums.service.ForumService;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */
@Controller
public class ForumsController {
	
	@SuppressWarnings("unused")
	private static final Logger log = Logger.getLogger(ForumsController.class);
	
	@Autowired
	private ForumService forumService;
	
	
	// ========================================================================
	// Dependency injection methods
	// ========================================================================
	
	public void setForumService(ForumService forumService) {
		this.forumService = forumService;
	}
	
	
	// ========================================================================
	// Service methods
	// ========================================================================
	
	@RequestMapping(value="/forums/home")
	public List<Forum> home() {
		return forumService.getForums();
	}
	
	/**
	 * <p>
	 * The JSP should use ${messageList} rather than ${forum.messages} if the
	 * authorized list of messages is desired.
	 * </p>
	 * 
	 * @param id
	 * @param model
	 */
	@RequestMapping
	public void forum(@RequestParam("id") Long id, Model model) {
		Assert.notNull(id, "id required");
		
		// This is a non-persistent forum, so we're free to perform
		// modifications like reverse.
		Forum forum = forumService.getForum(id);
		Collections.reverse(forum.getMessages());
		
		model.addAttribute(forum);
	}
	
	@RequestMapping
	public Message message(@RequestParam("id") Long id) {
		return forumService.getMessage(id);
	}
	
	@RequestMapping
	public Forum post(@RequestParam("forumId") Long forumId) {
		return forumService.getForum(forumId);
	}
	
	@RequestMapping
	public void account(Model model) {
		model.addAttribute("testText", forumService.getAccountInfo());
	}
	
	@RequestMapping
	public void admin(Model model) {
		model.addAttribute("testText", forumService.getAdminInfo());
	}
}
